package com.teacherprofile.manage.tools;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.teacherprofile.common.core.domain.entity.SysUser;
import com.teacherprofile.common.core.domain.model.LoginUser;
import com.teacherprofile.common.domain.SoftwareCopyrights;
import com.teacherprofile.common.enums.CheckStatus;

import com.teacherprofile.common.utils.SecurityUtils;
import com.teacherprofile.manage.domain.dto.ai.VideoGenerationRequest;
import com.teacherprofile.manage.service.ISoftwareCopyrightsService;
import com.teacherprofile.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.coyote.Response;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

import org.springframework.ai.zhipuai.ZhiPuAiChatModel;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class ServiceTools {
    private final ISoftwareCopyrightsService softwareCopyrightsService;
    private final ISysUserService sysUserService;
//    @Tool(description = "查询文章列表")
//    public List<SoftwareCopyrights> list(ToolContext context) {
//        System.out.println("查询软著中……");
//        String userName = (String) context.getContext().getOrDefault("user", SecurityUtils.getUsername());
//        SysUser sysUser = userService.selectUserByUserName(userName);
//        System.out.println("===========>"+sysUser);
//        SoftwareCopyrights softwareCopyrights = new SoftwareCopyrights();
//        QueryWrapper<SoftwareCopyrights> queryWrapper = new QueryWrapper<>(softwareCopyrights);
//        queryWrapper
//                .eq("del_flag", 0)
//                .eq("check_status", 0);
//        return softwareCopyrightsService.list(queryWrapper);
//    }

    @Tool(description = "根据用户名软著列表")
    public List<SoftwareCopyrights> softwareCopyrightsList(@ToolParam(description = "用户名") String userName) {

        return softwareCopyrightsService
                .lambdaQuery()
                .eq(SoftwareCopyrights::getUserName, userName)
                .list();

    }

    @Tool(description = "根据软著id审核软著")
    public void checkSoftware(@ToolParam(description = "软著id") List<Long> ids) {
        // 遍历软著id列表
        for (Long id : ids) {
            // 创建软著对象
            SoftwareCopyrights softwareCopyrights = new SoftwareCopyrights();
            // 设置软著id
            softwareCopyrights.setId(id);
            // 设置审核状态为通过
            softwareCopyrights.setCheckStatus(CheckStatus.WAITING_CHECK.getCode());
            // 调用审核方法
            softwareCopyrightsService.check(softwareCopyrights);
        }
        // 输出审核成果
        System.out.println("审核成功");
    }

    @Tool(description = "根据用户名查询对应的用户信息")
    public SysUser getUserByUserName(@ToolParam(description = "用户名") String userName) {
        // 根据用户名查询用户信息
        return sysUserService.selectUserByUserName(userName);
    }

    @Tool(description = "根据任务id查询视频任务")
    public String getVideoTaskByTaskId(@ToolParam(description = "视频任务id") String  taskId) {
        // 根据任务id查询视频任务
        System.out.println("根据任务id查询视频任务");
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://open.bigmodel.cn/api/paas/v4/async-result/" + taskId))
                .header("Authorization", "Bearer e047bb88077844569470444f28229a74.I7o87P7cUaGmXmtm")
                .header("Content-Type", "application/json")
                .GET()
                .build();

        try {
            HttpResponse<String> send = client.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println(send.body());
            return send.body();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }

    @Tool(description = "视频生成功能")
    public String videoGen(@ToolParam(description = "视频生成提示词") String prompt) {
        VideoGenerationRequest reqBody = new VideoGenerationRequest();
        HttpClient client = HttpClient.newHttpClient();
        reqBody = new VideoGenerationRequest(); // 初始化默认请求对象
        reqBody.setModel("CogVideoX-Flash"); // 设置默认模型
        reqBody.setQuality("quality"); // 设置默认质量
        reqBody.setPrompt("prompt"); // 设置默认提示词
        reqBody.setSize("1920x1080");
        reqBody.setWith_audio(true);
        reqBody.setFps(60);
        reqBody.setPrompt(prompt);
        log.info("视频生成请求参数: {}", reqBody);

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://open.bigmodel.cn/api/paas/v4/videos/generations"))
                .header("Authorization", "Bearer e047bb88077844569470444f28229a74.I7o87P7cUaGmXmtm")
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(JSONObject.toJSONString(reqBody)))
                .build();

        CompletableFuture<HttpResponse<String>> future = client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
        try {
            System.out.println(future.get().body());
            return future.get().body();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}